import router from '@/router';
import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenusById
} from '@/service/login/login';
import { localCache, mapMenusToRoutes } from '@/utils';
import { mapMenusToPermissions } from '@/utils/map-menus';
import { Module } from 'vuex';

import { IRootState } from '../types';
import { ILoginState } from './types';

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: [],
      permissions: []
    };
  },
  getters: {},
  mutations: {
    changeToken(state, token: string) {
      state.token = token;
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo;
    },
    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus;
      // 更新当前路由
      const routes = mapMenusToRoutes(userMenus);
      routes.forEach((route) => {
        router.addRoute('main', route);
      });
      const permissions = mapMenusToPermissions(userMenus);
      state.permissions = permissions;
    }
    // 获取用户按钮的权限
  },
  actions: {
    async accountLoginAction({ commit, dispatch }, payload: any) {
      // 1.登录逻辑
      const loginResult = await accountLoginRequest(payload);
      const { id, token } = loginResult.data;
      commit('changeToken', token);
      localCache.setCache('token', token);
      dispatch('getInitialDataAction', null, { root: true });

      // 2.请求用户信息
      const userInfoResult = await requestUserInfoById(id);
      const userInfo = userInfoResult.data;
      commit('changeUserInfo', userInfo);
      localCache.setCache('userInfo', userInfo);

      // 3.获取用户菜单信息
      const userMenusResult = await requestUserMenusById(userInfo?.role?.id);
      commit('changeUserMenus', userMenusResult.data);
      localCache.setCache('userMenus', userMenusResult.data);

      // 4.跳到首页
      router.push('/main');
    },
    // async phoneLoginAction({ commit }, payload: any) {}
    loadLocalLogin({ commit, dispatch }) {
      const token = localCache.getCache('token');
      if (token) {
        commit('changeToken', token);
        dispatch('getInitialDataAction', null, { root: true });
      }

      const userInfo = localCache.getCache('userInfo');
      userInfo && commit('changeUserInfo', userInfo);

      const userMenus = localCache.getCache('userMenus');
      userMenus && commit('changeUserMenus', userMenus);
    }
  }
};

export default loginModule;
